/**
 * Game starts the next level
 * 
 * created 11-18
 * @author Jonathan Odom
 */
package vooga.core;

import javax.swing.JOptionPane;

public class Game
{
	public static final String BROKEN_GAME_ERROR = "Cannot start game because if is broken or has missing files.";

	private VoogaView myView;
	private LevelFactoryInterface myLevelFactory;
	private ScoreSheet myHighScores;
	AbstractLevel myCurrLevel;
	
	/**
	 * 
	 * @param view the view that the game will be shown in
	 * @param levelClass should extend AbstractLevel
	 * @throws IllegalAccessException 
	 * @throws InstantiationException 
	 * @throws NoSuchMethodException 
	 * @throws SecurityException 
	 */
	public Game(VoogaView view, Class levelFactoryClass) throws InstantiationException, IllegalAccessException
	{
		myView = view;
		myLevelFactory = (LevelFactoryInterface)levelFactoryClass.newInstance();
	}

	public void nextLevel(Player player)
	{
		myView.resetLayers();
		switch (player.getStatus().getGameState()) {
		case INTRO:
			displayIntroLayer(player);
			break;
			//TODO: Add button on this screen to start game
		case RUNNING:
			try
			{
				//if next level from factory is null we should end
				myCurrLevel = myLevelFactory.getLevel(myView, player);
				if(myCurrLevel == null)
				{
					player.getStatus().setGameState(Status.GameState.WON);
					nextLevel(player);
				}
				else
				{
					myCurrLevel.start(this);
				}
				//we need level factory to tell when there are no more levels
			}
			catch(Exception e)
			{
				e.printStackTrace();
				myView.showError(BROKEN_GAME_ERROR);
			}
			break;
		case QUIT:
			finalizePlayer(player);
			break;
		case GAME_OVER:
			JOptionPane.showMessageDialog(null, "Game Over!");
			finalizePlayer(player);
			break;
		case WON:
			JOptionPane.showMessageDialog(null, "You Won!");
			finalizePlayer(player);
			break;
		default:
			break;
		}
	}

	public AbstractLevel getCurrLevel()
	{
		return myCurrLevel;
	}
	
	public void displayIntroLayer(Player player)
	{
		myHighScores = new ScoreSheet(player.getStatus().getGameName());
		player.getStatus().setGameState(Status.GameState.RUNNING); //hack for now
		nextLevel(player);

	}
	
	public void finalizePlayer(Player player)
	{
		player.getStatus().saveStatus();
		long tempScore = player.getStatus().getScore();
		String tempName = player.getName();
		myHighScores.addScore(new HighScore(tempName, tempScore));
		player.setStatus(new Status());
	}
}
